package com.qyxx.platform.dwr.reverseajax;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;

import com.google.common.collect.Lists;
import com.qyxx.platform.inf.jpush.Push;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.memo.entity.Memo;
import com.qyxx.platform.sysmng.memo.entity.MemoToUser;
import com.qyxx.platform.sysmng.utils.Constants;

/**
 *  @author tsd
 *  @version 1.0 2015-3-16 下午04:09:37
 *  @since jdk1.6 
 *  dwr推送
 */
public class Comet {
	
	private static final String IS_APP_LOGIN = "isAppLogin";//是否移动端登录

	/*
	 * 推送通知
	 * */
	public static void push(final Map<Long, Integer> userToNoticeNum, final Map<String, Integer> userToProcessTraceNum) {
		// TODO Auto-generated method stub
		if(userToNoticeNum != null && userToProcessTraceNum != null) {
			Browser.withAllSessionsFiltered (
				new ScriptSessionFilter() {
					public boolean match(ScriptSession s) {
						User user = (User)s.getAttribute(Constants.USER_SESSION_ID);
						if(user != null) {
							Integer i = userToNoticeNum.get(user.getId());
							Integer j = userToProcessTraceNum.get(user.getLoginName());
							if(i == null) i = 0;
							if(j == null) j = 0;
							/*Integer onum = (Integer)s.getAttribute("onum");
							Integer num = i + j;
					        if(num != onum) {
					        	//手机端推送--极光推送
					        	String isAppLogin = (String)s.getAttribute(IS_APP_LOGIN);
					        	if("true".equals(isAppLogin)) {
					        		String userId = String.valueOf(user.getId());
						        	String msg = "您有" + i + "条消息通知，" + j + "条待办事宜，请及时处理";
						        	Push.sendPushMsg(new String[]{userId}, msg);
					        	}
					        	//web端推送--dwr推送
					        	s.setAttribute("onum", num);
					        	ScriptBuffer sb = new ScriptBuffer("chengeNoticeNum('" + num + "')");
					        	s.addScript(sb);
					        }*/
							Integer noticeNum = (Integer)s.getAttribute("noticeNum");//通知数
							Integer approveNum = (Integer)s.getAttribute("approveNum");//审批数
					        List<String> result = Lists.newArrayList();
							if(i != noticeNum) {
					        	s.setAttribute("noticeNum", i);
					        	result.add("\"noticeNum\":" + i);
					        }
					        if(j != approveNum) {
					        	s.setAttribute("approveNum", j);
					        	result.add("\"approveNum\":" + j);
					        }
					        if(!result.isEmpty()) {
					        	//手机端推送--极光推送
					        	String isAppLogin = (String)s.getAttribute(IS_APP_LOGIN);
					        	if("true".equals(isAppLogin)) {
					        		String userId = String.valueOf(user.getId());
						        	String msg = "您有" + i + "条消息通知，" + j + "条待办事宜，请及时处理";
						        	Push.sendPushMsg(new String[]{userId}, msg);
					        	}
					        	String msg = "{" + StringUtils.join(result, ",") + "}";
					        	ScriptBuffer sb = new ScriptBuffer("chengeNoticeNum(" + msg + ")");
					        	s.addScript(sb);
					        }
						}
				        return false;
				    }
				}, new Runnable() {
				    public void run() {}
			    }
			);
		}
	}
	
	/*
	 * 推送备忘录提醒
	 * */
	public static void push(final Memo memo) {
		// TODO Auto-generated method stub
		if(memo != null) {
			Browser.withAllSessionsFiltered (
				new ScriptSessionFilter() {
					public boolean match(ScriptSession s) {
						User user = (User)s.getAttribute(Constants.USER_SESSION_ID);
						if(user != null && memo.getMtuUserId() != null && memo.getMtuUserId().equals(user.getId())) {
							ScriptBuffer sb = new ScriptBuffer();
							sb.appendScript("remindMemo(");
							sb.appendData(memo);
							sb.appendScript(");");
				        	s.addScript(sb);
						}
				        return false;
				    }
				}, new Runnable() {
				    public void run() {}
			    }
			);
		}
	}
	
	/*
	 * 将的备忘录删除消息，推送给正在被提醒用户
	 * */
	public static void push(final List<MemoToUser> list) {
		// TODO Auto-generated method stub
		if(list != null && !list.isEmpty()) {
			Browser.withAllSessionsFiltered (
				new ScriptSessionFilter() {
					public boolean match(ScriptSession s) {
						User user = (User)s.getAttribute(Constants.USER_SESSION_ID);
						List<MemoToUser> memoToUserList = new ArrayList<MemoToUser>();
						for(MemoToUser memoToUser : list) {
							if(user != null && memoToUser != null && memoToUser.getUserId() != null && memoToUser.getUserId().equals(user.getId())) {
								memoToUserList.add(memoToUser);
							}
						}
						if(!memoToUserList.isEmpty()) {
							ScriptBuffer sb = new ScriptBuffer();
							sb.appendScript("remindDeleteMemo(");
							sb.appendData(memoToUserList);
							sb.appendScript(");");
				        	s.addScript(sb);
						}
				        return false;
				    }
				}, new Runnable() {
				    public void run() {}
			    }
			);
		}
	}
	
	/*
	 * 保存连接信息
	 * */
	public void setUserIdAttribute(String isAppLogin) {
		// TODO Auto-generated method stub
		Object user = WebContextFactory.get().getSession().getAttribute(Constants.USER_SESSION_ID);
	    ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
	    scriptSession.setAttribute(Constants.USER_SESSION_ID, user);//设置用户session
	    scriptSession.setAttribute(IS_APP_LOGIN, isAppLogin);//设置是否移动端APP登录
    }
	
	/*
	 * 释放无用连接
	 * */
	public void invalidateScriptSession() {
		// TODO Auto-generated method stub
	    ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
	    scriptSession.invalidate();
    }
	
}
